export default class Deque<T> {
    private count: number;
    private lowestCount: number;
    private items: Map<number, T>;

    constructor() {
        this.count = 0;
        this.lowestCount = 0;
        this.items = new Map();
    }

    /**
     * @description: 在lowestCount方向（队列顶部）入队
     * @param {T} element
     */
    addFront(element: T): void {
        this.lowestCount--;
        this.items.set(this.lowestCount, element);
    }

    /**
     * @description: 在count方向（队列底部）入队
     * @param {T} element
     */
    addBack(element: T): void {
        this.items.set(this.count, element);
        this.count++;
    }

    /**
     * @description: 在lowestCount方向（队列顶部）出队
     * @return {T} element
     */
    removeFront(): T | undefined {
        if (this.isEmpty()) {
            return undefined;
        }
        const result = this.items.get(this.lowestCount);
        this.items.delete(this.lowestCount);
        this.lowestCount++;
        return result;
    }

    /**
     * @description: 在count方向（队列底部）出队
     * @return {T} element
     */
    removeBack(): T | undefined {
        if (this.isEmpty()) {
            return undefined;
        }
        this.count--;
        const result = this.items.get(this.count);
        this.items.delete(this.count);
        return result;
    }

    /**
     * @description: 返回队列顶部的元素
     * @return {T} element
     */
    peekFront(): T | undefined {
        if (this.isEmpty()) {
            return undefined;
        }
        return this.items.get(this.lowestCount);
    }

    /**
     * @description: 返回队列底部的元素
     * @return {T} element
     */
    peekBack(): T | undefined {
        if (this.isEmpty()) {
            return undefined;
        }
        return this.items.get(this.count - 1);
    }

    /**
     * @description: 返回队列是否为空
     * @return {Boolean}
     */
    isEmpty(): boolean {
        return this.items.size === 0;
    }

    /**
     * @description: 清空队列
     */
    clear(): void {
        this.items = new Map();
        this.count = 0;
        this.lowestCount = 0;
    }

    /**
     * @description: 返回队列元素的数目
     * @return {Number}
     */
    size(): number {
        return this.items.size;
    }

    /**
     * @description: 覆盖Object默认的toString
     * @return {String}
     */
    toString(): string {
        if (this.isEmpty()) {
            return '';
        }
        let objString: string = `${this.items.get(this.lowestCount)}`;
        for (let i = this.lowestCount + 1; i < this.count; i++) {
            objString = `${objString},${this.items.get(i)}`;
        }
        return objString;
    }
}